package com.files.parse.controller;


import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.parser.pdf.PDFParser;
import org.apache.tika.sax.BodyContentHandler;
import org.aspectj.util.FileUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @author 袁强
 * @version 2024年10月17日 21:31:30
 */
@RestController
@RequestMapping("/")
//@Data
public class TestController{

	@RequestMapping("/test")
	@ResponseBody
	public Object bootstrap() {
		return "success~";
	}

	@Value("#{systemProperties['user.dir']}")
	private String localPicPath;

	@RequestMapping("/fileUpload1")
	@ResponseBody
	public void fileUploadByPDFBox(@RequestParam("files") MultipartFile[] files) throws Exception {
		for (MultipartFile file:files) {
			InputStream inputStream = file.getInputStream();
			byte[] bytes = FileUtil.readAsByteArray(inputStream);
			inputStream = new ByteArrayInputStream(bytes);
			PDDocument doc = PDDocument.load(inputStream);
			int pageCount = doc.getNumberOfPages();
			PDFRenderer renderer = new PDFRenderer(doc);
			//todo 将 pdf 转换成 图片png
		    for (int i = 0; i < pageCount; i++) {
				String singleUuid = UUID.randomUUID().toString().replace("-", "");
				String singleLocalPath = localPicPath + "/" + singleUuid + ".png";
				BufferedImage bufferedImage = renderer.renderImageWithDPI(i, 120, ImageType.RGB);
				if (bufferedImage.getHeight() > 3000 || bufferedImage.getWidth() > 3000) {
					bufferedImage = renderer.renderImageWithDPI(i, 30, ImageType.RGB);
				}
				ImageIO.write(bufferedImage, "png", new File(singleLocalPath));
			}

			//todo 识别 pdf 内容，缺点：pdf 所有内容识别成字符串，以空格和换行分割，没有格式，二次处理有困难
			List<String> extractedTexts = new ArrayList<>();
			PDFTextStripper stripper = new PDFTextStripper();
			String text = stripper.getText(doc);
			extractedTexts.add(text);

			doc.close();
			inputStream.close();
		}
	}

	@RequestMapping("/fileUpload2")
	@ResponseBody
	public void fileUploadByTikaPDF(@RequestParam("files") MultipartFile[] files) throws Exception{
		for (MultipartFile file:files) {
			tikaPDFExtractor(file.getInputStream());
		}
	}

	public void tikaPDFExtractor(InputStream inputStream){
		try {
			// 创建解析上下文
			ParseContext context = new ParseContext();
			// 创建 PDF 解析器
			PDFParser parser = new PDFParser();
			// 创建内容处理器，用于存储提取的文本
			BodyContentHandler handler = new BodyContentHandler();
			// 读取 PDF 文件
			Metadata metadata = new Metadata();
			// 解析 PDF 文件
			parser.parse(inputStream, handler, metadata, context);
			// 打印提取的文本
			System.out.println(handler.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
